package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.dao.KcOrdersMapper;
import com.etalk.crm.dao.StuAutoBookClassTimeMapper;
import com.etalk.crm.pojo.AutoBookClassRecord;
import com.etalk.crm.pojo.AutoCourseLog;
import com.etalk.crm.pojo.AutoCourseLogMap;
import com.etalk.crm.pojo.StuAutoBookClassTime;
import com.etalk.crm.service.StuAutoBookClassTimeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jordan
 * @date 2019/6/14 15:54
 * @description
 */
@Service
public class StuAutoBookClassTimeServiceImpl implements StuAutoBookClassTimeService {
    private static final Logger logger = LogManager.getLogger(StuAutoBookClassTimeServiceImpl.class);
    @Resource
    private StuAutoBookClassTimeMapper stuAutoBookClassTimeMapper;
    @Resource
    private KcOrdersMapper kcOrdersMapper;

    /**
     * 获取偏好设置页面数据
     * @param personId  学员id
     * @return 记录
     */
    @Override
    public List<AutoBookClassRecord> searchAutoBookClassTimeByPersonId(int personId) {
        List<StuAutoBookClassTime> stuAutoBookClassTimeList=stuAutoBookClassTimeMapper.selectAutoBookClassTimeByPersonId(personId,"",null);
        List<AutoBookClassRecord> list=new ArrayList<>();
        AutoBookClassRecord autoBookClassRecord=new AutoBookClassRecord();
        String tempOrderId = "";
        for (StuAutoBookClassTime record:stuAutoBookClassTimeList){
            if (!record.getOrderId().equals(tempOrderId)) {
                if(!"".equals(tempOrderId)) {
                    autoBookClassRecord = new AutoBookClassRecord();
                }
                tempOrderId=record.getOrderId();
                autoBookClassRecord.setOrderId(record.getOrderId());
                String orderState="";
                switch (record.getOrderState()){
                    case 0:
                        orderState="<strong style='color:red;'>无效</strong>";
                        break;
                    case 1:
                        orderState="<strong style='color:green;'>正常</strong>";
                        break;
                    case 2:
                        orderState="<strong style='color:red;'>已学完</strong>";
                        break;
                    case 3:
                        orderState="<strong style='color:red;'>已到期</strong>";
                        break;
                    case 4:
                        orderState="<strong style='color:yellow;'>已冻结</strong>";
                        break;
                    default:
                }
                autoBookClassRecord.setOrderName(record.getOrderName()+"("+orderState+")<br/>"+record.getMaterialName());
                list.add(autoBookClassRecord);
            }
            switch (record.getWeekId()){
                case 1:
                    autoBookClassRecord.getListMonday().add(record.getClassTime());
                    break;
                case 2:
                    autoBookClassRecord.getListTuesday().add(record.getClassTime());
                    break;
                case 3:
                    autoBookClassRecord.getListWednesday().add(record.getClassTime());
                    break;
                case 4:
                    autoBookClassRecord.getListThursday().add(record.getClassTime());
                    break;
                case 5:
                    autoBookClassRecord.getListFriday().add(record.getClassTime());
                    break;
                case 6:
                    autoBookClassRecord.getListSaturday().add(record.getClassTime());
                    break;
                case 7:
                    autoBookClassRecord.getListSunday().add(record.getClassTime());
                    break;
                default:break;
            }

        }
        stuAutoBookClassTimeList.clear();
        logger.info(JSON.toJSONString(list));
        return list;
    }

    /**
     * 初始化自动约课页面数据
     * @param personId 用户id
     * @param orderId 订单id
     * @param weekId 星期几
     * @return 数据
     */
    @Override
    public Map<String,Object> searchAutoBookClassSetup(int personId,String orderId,int weekId){
        Map<String,Object> resultMap=new HashMap<>(3);
        //查询已设置的时间
        List<StuAutoBookClassTime> stuAutoBookClassTimeList=null;
        if (StringUtils.isNotEmpty(orderId) && weekId>0){
            stuAutoBookClassTimeList=stuAutoBookClassTimeMapper.selectAutoBookClassTimeByPersonId(personId,orderId,weekId);
            resultMap.put("weekId",weekId);
            resultMap.put("orderId",orderId);
        }
        //时间按钮列表和按钮状态
        List<Map<String,Object>> localTimeList=new ArrayList<>(48);
        LocalTime startLocalTime=LocalTime.parse("08:00:00");
        LocalTime endLocalTime=LocalTime.parse("23:00:00");
        Map<String,Object> tempMap;
        while (startLocalTime.isBefore(endLocalTime)){
            tempMap=new HashMap<>(3);
            //按钮显示时间
            tempMap.put("time",startLocalTime);
            //按钮状态
            tempMap.put("state", 0);
            if (stuAutoBookClassTimeList!=null && stuAutoBookClassTimeList.size()>0) {
                //更新按钮状态
                if (startLocalTime.equals(stuAutoBookClassTimeList.get(0).getClassTime())){
                    tempMap.put("state", 1);
                }else if (startLocalTime.isAfter(stuAutoBookClassTimeList.get(0).getClassTime())){
                    int stuAutoBookClassTimeListSize=stuAutoBookClassTimeList.size();
                    for (int i=1;i<stuAutoBookClassTimeListSize;i++) {
                        if (stuAutoBookClassTimeList.get(i).getClassTime().equals(startLocalTime)) {
                            tempMap.put("state", 1);
                            break;
                        }
                    }
                }
            }
            localTimeList.add(tempMap);
            startLocalTime=startLocalTime.plusMinutes(20);
        }
        resultMap.put("listTime",localTimeList);
        resultMap.put("orders",kcOrdersMapper.selectTradeOrderMaterialByPersonId(personId,weekId,orderId));

        return resultMap;
    }

    /**
     * 添加自动约课信息
     *
     * @param personId   用户id
     * @param orders     订单数组
     * @param weekIds    星期数组
     * @param localTimes 约课时间
     * @return 结果
     */
    @Override
    public int addAutoBookedClassSetup(int personId, String[] orders, Integer[] weekIds, List<LocalTime> localTimes,String creator) {
        List<StuAutoBookClassTime> stuAutoBookClassTimeList=new ArrayList<>();
        StuAutoBookClassTime record;
        for (String orderId:orders){
            for (int weekId:weekIds){
                if (localTimes!=null && localTimes.size()>0) {
                    for (LocalTime classTime : localTimes) {
                        record = new StuAutoBookClassTime();
                        record.setPersonId(personId);
                        record.setOrderId(orderId);
                        record.setWeekId(weekId);
                        record.setClassTime(classTime);
                        record.setCreator(creator);
                        stuAutoBookClassTimeList.add(record);
                    }
                }else {
                    record = new StuAutoBookClassTime();
                    record.setPersonId(personId);
                    record.setOrderId(orderId);
                    record.setWeekId(weekId);
                    record.setCreator(creator);
                    stuAutoBookClassTimeList.add(record);
                }
            }
        }
        int num=0;
        if (stuAutoBookClassTimeList.size()>0){
            logger.info("自动约课参数：[{}]",JSON.toJSONString(stuAutoBookClassTimeList));
            //删除原有记录
            num=stuAutoBookClassTimeMapper.delete(stuAutoBookClassTimeList);
            if (localTimes!=null && localTimes.size()>0) {
                //添加新记录
                num += stuAutoBookClassTimeMapper.insert(stuAutoBookClassTimeList);
            }
        }

        return num;
    }

    /**
     * 查询自动约课结果
     * @param record 查询条件
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 列表
     */
    @Override
    public PageInfo<AutoCourseLogMap> searchAutoCourseLogByPage(AutoCourseLog record, int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<AutoCourseLogMap> list=stuAutoBookClassTimeMapper.selectAutoCourseLogByPage(record);
        if (list!=null && list.size()>0){
            for (AutoCourseLogMap autoCourseLog:list){
                JSONObject result=JSON.parseObject(autoCourseLog.getResult());
                if (result.getInteger("status")==0){
                    autoCourseLog.setResult(result.getString("msg"));
                }else {
                    autoCourseLog.setResult(result.getJSONObject("data").toJSONString());
                }
            }
        }
        return new PageInfo<>(list);
    }

}
